#ifndef PALETTE_WIDGET_H
#define PALETTE_WIDGET_H

#undef min
#undef max

#include <QWidget>

namespace widgets {
  class Palette : public QWidget
  {
    Q_OBJECT

  public: // methods
    Palette(QWidget *parent = 0);
    ~Palette();

    QGradientStops stops() const;
    qreal min() const;
    qreal max() const;

  public slots:
    void setStops(const QGradientStops &gradient);
    void setMinMax(qreal min, qreal max);
signals:
      void stopsChanged(const QGradientStops &gradient);

  public:
    static QGradientStops load_stops(const QString &file_path);

  protected:
    virtual void paintEvent(QPaintEvent *);
    virtual void mouseDoubleClickEvent(QMouseEvent *);
    virtual void mousePressEvent(QMouseEvent *);
    virtual void mouseReleaseEvent(QMouseEvent *);
    virtual void mouseMoveEvent(QMouseEvent *);
    virtual void contextMenuEvent(QContextMenuEvent *);

  private: // private methods
    QRect get_gradient_rect() const;
    QRect get_stop_rect(const QGradientStop &stop) const;
    qreal nearest(const QPoint &pos) const;
    int hit_test(const QPoint &pos, qreal *p_nearest = 0) const;
    void insert_anchor(qreal pos);
    void choose_anchor_color(size_t index);
    private slots:
      void on_action_insert_anchor();
      void on_action_remove_anchor();
      void on_action_set_anchor_color();
      void on_action_load_palette();
      void on_action_save_palette();

  private: // private fields
    static const int anchor_width = 15;
    static const int anchor_height = 15;
    static const int border = 5;
    static const int tick_size = 10;
    static const int tick_label_space = 3;
    static const int gradient_width_ = 50;
    //  int label_width_;
    int label_height_;
    QGradientStops stops_;
    qreal min_;
    qreal max_;
    int tracking_anchor_;
    QAction *p_action_load_palette_;
    QAction *p_action_save_palette_;
    QAction *p_action_insert_anchor_;
  };
} // namespace widgets {
#endif // PALETTE_WIDGET_H
